home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 4 / Apprentice-Release4.iso / Languages / MPW Oberon 2.1168 / OExamples / Sample.mod < prev    next >
Encoding:
Text File  |  1995-07-03  |  33.5 KB  |  917 lines  |  [TEXT/MPS ]

  1. (*------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    MultiFinder-Aware Simple Sample Application
  6. #
  7. #    Sample
  8. #
  9. #    Sample.p    -    Pascal Source
  10. #
  11. #    Copyright © 1989 Apple Computer, Inc.
  12. #    All rights reserved.
  13. #
  14. #    Versions:    
  15. #                1.00                08/88
  16. #                1.01                11/88
  17. #                1.02                04/89    MPW 3.1
  18. #                1.03                02/90    MPW 3.2
  19. #
  20. #    Components:
  21. #                Sample.p            Feb.  1, 1990
  22. #                Sample.r            Feb.  1, 1990
  23. #                Sample.h            Feb.  1, 1990
  24. #                Sample.make            Feb.  1, 1990
  25. #
  26. #    Sample is an example application that demonstrates how to
  27. #    initialize the commonly used toolbox managers, operate 
  28. #    successfully under MultiFinder, handle desk accessories, 
  29. #    and create, grow, and zoom windows.
  30. #
  31. #    It does not by any means demonstrate all the techniques 
  32. #    you need for a large application. In particular, Sample 
  33. #    does not cover exception handling, multiple windows/documents, 
  34. #    sophisticated memory management, printing, or undo. All of 
  35. #    these are vital parts of a normal full-sized application.
  36. #
  37. #    This application is an example of the form of a Macintosh 
  38. #    application; it is NOT a template. It is NOT intended to be 
  39. #    used as a foundation for the next world-class, best-selling, 
  40. #    600K application. A stick figure drawing of the human body may 
  41. #    be a good example of the form for a painting, but that does not 
  42. #    mean it should be used as the basis for the next Mona Lisa.
  43. #
  44. #    We recommend that you review this program or TESample before 
  45. #    beginning a new application.
  46. #
  47. ------------------------------------------------------------------------------*)
  48.  
  49.  
  50. MODULE Sample;
  51.  
  52.  
  53. (*Segmentation strategy:
  54.  
  55.  This program consists of three segments. Main contains most of the code,
  56.  including the MPW libraries, and the main program. Initialize contains
  57.  code that is only used once, during startup, and can be unloaded after the
  58.  program starts. %A5Init is automatically created by the Linker to initialize
  59.  globals for the MPW libraries and is unloaded right away.*)
  60.  
  61.  
  62. (*SetPort strategy:
  63.  
  64.  Toolbox routines do not change the current port. In spite of this, in this
  65.  program we use a strategy of calling SetPort whenever we want to draw or
  66.  make calls which depend on the current port. This makes us less vulnerable
  67.  to bugs in other software which might alter the current port (such as the
  68.  bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  69.  Hopefully, this also makes the routines from this program more self-contained,
  70.  since they don't depend on the current port setting.*)
  71.  
  72. IMPORT SYSTEM, Traps, Types, OSUtils, Quickdraw, Windows, Dialogs,
  73.        SegLoad, Desk, Events, Fonts, Menus, TextEdit, Memory, DiskInit,
  74.        ToolUtils, Resources;
  75.  
  76. CONST
  77.     (*MPW 3.0 will include a Traps.p interface file that includes constants for trap numbers.
  78.      These constants are from that file.*)
  79.     (*1.02 - since using MPW 3.0 only, we include Traps.p, so we now have trap numbers.*)
  80.  
  81.     (*1.01 - changed constants to begin with 'k' for consistency, except for resource IDs*)
  82.     (*SysEnvironsVersion is passed to SysEnvirons to tell it which version of the
  83.      SysEnvRec we understand.*)
  84.     kSysEnvironsVersion        = 1;
  85.  
  86.     (*OSEvent is the event number of the suspend/resume and mouse-moved events sent
  87.      by MultiFinder. Once we determine that an event is an osEvent, we look at the
  88.      high byte of the message sent to determine which kind it is. To differentiate
  89.      suspend and resume events we check the resumeMask bit.*)
  90.     kOSEvent                = Events.app4Evt;    (*event used by MultiFinder*)
  91.     kSuspendResumeMessage    = 1;        (*high byte of suspend/resume event message*)
  92.     kResumeMask                = 1;        (*bit of message field for resume vs. suspend*)
  93.     kNoEvents                = 0;        (*no events mask*)
  94.  
  95.     (*1.01 - kMinHeap - This is the minimum result from the following
  96.      equation:
  97.             
  98.             ORD(GetApplLimit) - ORD(ApplicZone)
  99.             
  100.      for the application to run. It will insure that enough memory will
  101.      be around for reasonable-sized scraps, FKEYs, etc. to exist with the
  102.      application, and still give the application some 'breathing room'.
  103.      To derive this number, we ran under a MultiFinder partition that was
  104.      our requested minimum size, as given in the 'SIZE' resource.*)
  105.      
  106.     kMinHeap    = 21 * 1024;
  107.     
  108.     (*1.01 - kMinSpace - This is the minimum result from PurgeSpace, when called
  109.      at initialization time, for the application to run. This number acts
  110.      as a double-check to insure that there really is enough memory for the
  111.      application to run, including what has been taken up already by
  112.      pre-loaded resources, the scrap, code, and other sundry memory blocks.*)
  113.      
  114.     kMinSpace    = 8 * 1024;
  115.     
  116.     (*kExtremeNeg and kExtremePos are used to set up wide open rectangles and regions.*)
  117.     kExtremeNeg    = -32768;
  118.     kExtremePos    = 32767 - 1;            (*required for old region bug*)
  119.     
  120.     (*The following constants are all resource IDs, corresponding to resources in Sample.r.*)
  121.     rMenuBar    = 128;                    (*application's menu bar*)
  122.     rAboutAlert    = 128;                    (*about alert*)
  123.     rUserAlert    = 129;                    (*error user alert*)
  124.     rWindow        = 128;                    (*application's window*)
  125.     rStopRect    = 128;                    (*rectangle for Stop light*)
  126.     rGoRect        = 129;                    (*rectangle for Go light*)
  127.  
  128.     (*The following constants are used to identify menus and their items. The menu IDs
  129.      have an "m" prefix and the item numbers within each menu have an "i" prefix.*)
  130.     mApple        = 128;                    (*Apple menu*)
  131.     iAbout        = 1;
  132.  
  133.     mFile        = 129;                    (*File menu*)
  134.     iNew        = 1;
  135.     iClose        = 4;
  136.     iQuit        = 12;
  137.  
  138.     mEdit        = 130;                    (*Edit menu*)
  139.     iUndo        = 1;
  140.     iCut        = 3;
  141.     iCopy        = 4;
  142.     iPaste        = 5;
  143.     iClear        = 6;
  144.  
  145.     mLight        = 131;                    (*Light menu*)
  146.     iStop        = 1;
  147.     iGo            = 2;
  148.     
  149.     (*1.01 - kDITop and kDILeft are used to locate the Disk Initialization dialogs.*)
  150.     kDITop        = $0050;
  151.     kDILeft        = $0070;
  152.  
  153.  
  154. VAR
  155.     (*The "g" prefix is used to emphasize that a variable is global.*)
  156.  
  157.     (*GMac is used to hold the result of a SysEnvirons call. This makes
  158.      it convenient for any routine to check the environment. It is
  159.      global information, anyway.*)
  160.     gMac                : OSUtils.SysEnvRec;    (*set up by Initialize*)
  161.  
  162.     (*GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  163.      trap is available. If it is false, we know that we must call GetNextEvent.*)
  164.     gHasWaitNextEvent    : BOOLEAN;        (*set up by Initialize*)
  165.  
  166.     (*GInBackground is maintained by our osEvent handling routines. Any part of
  167.      the program can check it to find out if it is currently in the background.*)
  168.     gInBackground        : BOOLEAN;        (*maintained by Initialize and DoEvent*)
  169.  
  170.  
  171.     (*The following globals are the state of the window. If we supported more than
  172.      one window, they would be attatched to each document, rather than globals.*)
  173.  
  174.     (*GStopped tells whether the stop light is currently on stop or go.*)
  175.     gStopped            : BOOLEAN;        (*maintained by Initialize and SetLight*)
  176.  
  177.     (*GStopRect and gGoRect are the rectangles of the two stop lights in the window.*)
  178.     gStopRect            : Types.Rect;            (*set up by Initialize*)
  179.     gGoRect                : Types.Rect;            (*set up by Initialize*)
  180.  
  181.  
  182. (*$S Initialize*)
  183. PROCEDURE TrapAvailable(tNumber: INTEGER; tType: OSUtils.TrapType): BOOLEAN;
  184.  
  185. (*Check to see if a given trap is implemented. This is only used by the
  186.  Initialize routine in this program, so we put it in the Initialize segment.
  187.  The recommended approach to see if a trap is implemented is to see if
  188.  the address of the trap routine is the same as the address of the
  189.  Unimplemented trap.*)
  190. (*1.02 - Needs to be called after call to SysEnvirons so that it can check
  191.  if a ToolTrap is out of range of a pre-MacII ROM.*)
  192.  
  193. BEGIN
  194.     IF (tType = OSUtils.ToolTrap) &
  195.         (gMac.machineType > OSUtils.envMachUnknown) &
  196.         (gMac.machineType < OSUtils.envMacII) THEN        (*it's a 512KE, Plus, or SE*)
  197.         tNumber := BAND(tNumber, $03FF);
  198.         IF tNumber > $01FF THEN                            (*which means the tool traps*)
  199.             tNumber := Traps._Unimplemented                    (*only go to $01FF*)
  200.         END
  201.     END;
  202.     RETURN OSUtils.NGetTrapAddress(tNumber, tType) #
  203.             OSUtils.GetTrapAddress(Traps._Unimplemented);
  204. END TrapAvailable;
  205.  
  206.  
  207. (*$S Main*)
  208. PROCEDURE IsDAWindow(window: Windows.WindowPtr): BOOLEAN;
  209.  
  210. (*Check if a window belongs to a desk accessory.*)
  211.  
  212. BEGIN
  213.     IF window = NIL THEN
  214.         RETURN FALSE
  215.     ELSE    (*DA windows have negative windowKinds*)
  216.         RETURN window.windowKind < 0
  217.     END
  218. END IsDAWindow;
  219.  
  220.  
  221. (*$S Main*)
  222. PROCEDURE IsAppWindow(window: Windows.WindowPtr): BOOLEAN;
  223.  
  224. (*Check to see if a window belongs to the application. If the window pointer
  225.  passed was NIL, then it could not be an application window. WindowKinds
  226.  that are negative belong to the system and windowKinds less than userKind
  227.  are reserved by Apple except for windowKinds equal to dialogKind, which
  228.  mean it is a dialog.
  229.  1.02 - In order to reduce the chance of accidentally treating some window
  230.  as an AppWindow that shouldn't be, we'll only return true if the windowkind
  231.  is userKind. If you add different kinds of windows to Sample you'll need
  232.  to change how this all works.*)
  233.  
  234. BEGIN
  235.     IF window = NIL THEN
  236.         RETURN FALSE
  237.     ELSE    (*application windows have windowKinds = userKind (8)*)
  238.         RETURN window.windowKind = Windows.userKind
  239.     END
  240. END IsAppWindow;
  241.  
  242.  
  243. (*$S Main*)
  244. PROCEDURE AlertUser;
  245.  
  246. (*Display an alert that tells the user an error occurred, then exit the program.
  247.  This routine is used as an ultimate bail-out for serious errors that prohibit
  248.  the continuation of the application. Errors that do not require the termination
  249.  of the application should be handled in a different manner. Error checking and
  250.  reporting has a place even in the simplest application. For simplicity, the alert
  251.  displayed here only says that an error occurred, but not what it was. There are
  252.  various methods available for being more specific.*)
  253.  
  254. VAR
  255.     itemHit    : INTEGER;
  256. BEGIN
  257.     Quickdraw.SetCursor(Quickdraw.arrow);
  258.     itemHit := Dialogs.Alert(rUserAlert, NIL);
  259.     SegLoad.ExitToShell;
  260. END AlertUser;
  261.  
  262.  
  263. (*$S Main*)
  264. PROCEDURE DoCloseWindow(window: Windows.WindowPtr) : BOOLEAN;
  265.  
  266. (*Close a window.*)
  267.  
  268. (*1.01 - At this point, if there was a document associated with a
  269.  window, you could do any document saving processing if it is 'dirty'.
  270.  DoCloseWindow would return TRUE if the window actually closes, i.e.,
  271.  the user does not cancel from a save dialog. This result is handy when
  272.  the user quits an application, but then cancels a save of a document
  273.  associated with a window. We also added code to close the application
  274.  window since otherwise, the termination routines would never stop looping,
  275.  waiting for FrontWindow to return NIL.*)
  276.  
  277. BEGIN
  278.     IF IsDAWindow(window) THEN
  279.         Desk.CloseDeskAcc(window.windowKind)
  280.     ELSIF IsAppWindow(window) THEN
  281.         Windows.CloseWindow(window)
  282.     END;
  283.     RETURN TRUE
  284. END DoCloseWindow;
  285.  
  286.  
  287. (*$S Initialize*)
  288. PROCEDURE GoGetRect(rectID: INTEGER; VAR theRect: Types.Rect) : BOOLEAN;
  289.  
  290. (*This utility loads the global rectangles that are used by the window
  291.  drawing routines. It shows how the resource manager can be used to hold
  292.  values in a convenient manner. These values are then easily altered without
  293.  having to re-compile the source code. In this particular case, we know
  294.  that this routine is being called at initialization time. Therefore,
  295.  if this returns FALSE, we will assume that the application is in such
  296.  bad shape that we should just exit. Your error handling may differ, but
  297.  the check should still be made.*)
  298.  
  299. (*1.01 - Changed GoGetRect to return a BOOLEAN that indicates if it was successful
  300.  in getting the rectangle rather than just doing ExitToShell.*)
  301.  
  302. VAR
  303.     resource    : Types.Handle;
  304. BEGIN
  305.     resource := Resources.GetResource(LONG("RECT"), rectID);
  306.     IF resource # NIL THEN
  307.         SYSTEM.GET(MASTERPTR(resource), theRect)
  308.     END;
  309.     RETURN resource#NIL
  310. END GoGetRect;
  311.  
  312.  
  313. (*$S Initialize*)
  314. PROCEDURE Initialize;
  315.  
  316. (*Set up the whole world, including global variables, Toolbox managers,
  317.  and menus. We also create our one application window at this time.
  318.  Since window storage is non-relocateable, how and when to allocate space
  319.  for windows is very important so that heap fragmentation does not occur.
  320.  Because Sample has only one window and it is only disposed when the application
  321.  quits, we will allocate its space here, before anything that might be a locked
  322.  relocatable object gets into the heap. This way, we can force its storage to be
  323.  in the lowest memory available in the heap. Window storage can differ widely
  324.  amongst applications depending on how many windows are created and disposed.
  325.  If a failure occurs here, we will consider that the application is in such
  326.  bad shape that we should just exit. Your error handling may differ, but
  327.  the checks should still be made.*)
  328.  
  329. (*1.01 - The code that used to be part of ForceEnvirons has been moved into
  330.  this module. If an error is detected, instead of merely doing an ExitToShell,
  331.  which leaves the user without much to go on, we call AlertUser, which puts
  332.  up a simple alert that just says an error occurred and then calls ExitToShell.
  333.  In the interests of keeping things simple, the alert does not state the specific
  334.  cause of the error, but a more informative alert would be appropriate for more
  335.  sophisticated applications. Since there is no other cleanup needed at this point
  336.  if an error is detected, this form of error- handling is acceptable. If more
  337.  sophisticated error recovery is needed, a signal mechanism, such as is provided
  338.  by Signals, can be used.*)
  339.  
  340. VAR
  341.     menuBar            : Types.Handle;
  342.     window            : Windows.WindowPtr;
  343.     ignoreError        : Types.OSErr;
  344.     total, contig    : LONGINT;
  345.     ignoreResult    : BOOLEAN;
  346.     event            : Events.EventRecord;
  347.     count            : INTEGER;
  348.  
  349. BEGIN
  350.     gInBackground := FALSE;
  351.  
  352.     Quickdraw.InitGraf(Quickdraw.thePort);
  353.     Fonts.InitFonts;
  354.     Windows.InitWindows;
  355.     Menus.InitMenus;
  356.     TextEdit.TEInit;
  357.     Dialogs.InitDialogs(NIL);
  358.     Quickdraw.InitCursor;
  359.     
  360.     (*Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  361.      if you are using it.*)
  362.     (*NOTE -- It is no longer necessary, and actually unhealthy, to check
  363.      PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  364.      of checking for port availability themselves.*)
  365.     
  366.     (*This next bit of code is necessary to allow the default button of our
  367.      alert be outlined.
  368.      1.02 - Changed to call EventAvail so that we don't lose some important
  369.      events.*)
  370.      
  371.     FOR count := 1 TO 3 DO
  372.         ignoreResult := Events.EventAvail(Events.everyEvent, event)
  373.     END;
  374.     
  375.     (*Ignore the error returned from SysEnvirons; even if an error occurred,
  376.      the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  377.      call to SysEnvirons by calling it after initializing AppleTalk.*)
  378.      
  379.     ignoreError := OSUtils.SysEnvirons(kSysEnvironsVersion, gMac);
  380.     
  381.     (*Make sure that the machine has at least 128K ROMs. If it doesn't, exit.*)
  382.     
  383.     IF gMac.machineType < 0 THEN AlertUser END;
  384.     
  385.     (*1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  386.      in TrapAvailable if a tool trap value is out of range.*)
  387.      
  388.     gHasWaitNextEvent := TrapAvailable(Traps._WaitNextEvent, OSUtils.ToolTrap);
  389.  
  390.     (*1.01 - We used to make a check for memory at this point by examining ApplLimit,
  391.      ApplicZone, and StackSpace and comparing that to the minimum size we told
  392.      MultiFinder we needed. This did not work well because it assumed too much about
  393.      the relationship between what we asked MultiFinder for and what we would actually
  394.      get back, as well as how to measure it. Instead, we will use an alternate
  395.      method comprised of two steps.*)
  396.      
  397.     (*It is better to first check the size of the application heap against a value
  398.      that you have determined is the smallest heap the application can reasonably
  399.      work in. This number should be derived by examining the size of the heap that
  400.      is actually provided by MultiFinder when the minimum size requested is used.
  401.      The derivation of the minimum size requested from MultiFinder is described
  402.      in Sample.h. The check should be made because the preferred size can end up
  403.      being set smaller than the minimum size by the user. This extra check acts to
  404.      insure that your application is starting from a solid memory foundation.*)
  405.      
  406.     IF LONGINT(Memory.GetApplLimit()) - LONGINT(Memory.ApplicZone()) < kMinHeap THEN AlertUser END;
  407.     
  408.     (*Next, make sure that enough memory is free for your application to run. It
  409.      is possible for a situation to arise where the heap may have been of required
  410.      size, but a large scrap was loaded which left too little memory. To check for
  411.      this, call PurgeSpace and compare the result with a value that you have determined
  412.      is the minimum amount of free memory your application needs at initialization.
  413.      This number can be derived several different ways. One way that is fairly
  414.      straightforward is to run the application in the minimum size configuration
  415.      as described previously. Call PurgeSpace at initialization and examine the value
  416.      returned. However, you should make sure that this result is not being modified
  417.      by the scrap's presence. You can do that by calling ZeroScrap before calling
  418.      PurgeSpace. Make sure to remove that call before shipping, though.*)
  419.      
  420.     Memory.PurgeSpace(total, contig);
  421.     IF total < kMinSpace THEN AlertUser END;
  422.  
  423.     (*The extra benefit to waitng until after the Toolbox Managers have been initialized
  424.      before checking memory is that we can now give the user an alert to tell him what
  425.      happened. Although it is possible that the memory situation could be worsened by
  426.      displaying an alert, MultiFinder would gracefully exit the application with
  427.      an informative alert if memory became critical. Here we are acting more
  428.      in a preventative manner to avoid future disaster from low-memory problems.*)
  429.      
  430.     (*We will allocate our own window storage instead of letting the Window
  431.      Manager for two reasons. One, GetNewWindow locks the 'WIND' resource
  432.      handle before calling NewWindow and this can lead to heap fragmentation.
  433.      Two, it takes just as much time for NewWindow to get the memory as it
  434.      does for us to get it.*)
  435.  
  436.     window := Windows.WindowPtr(Memory.NewPtr(SIZE(Windows.WindowRecord)));
  437.     IF window = NIL THEN AlertUser END;
  438.     window := Windows.GetNewWindow(rWindow, Types.Ptr(window), Windows.WindowPtr(-1));
  439.  
  440.     menuBar := Menus.GetNewMBar(rMenuBar);        (*read menus into menu bar*)
  441.     IF menuBar = NIL THEN AlertUser END;
  442.     Menus.SetMenuBar(menuBar);                    (*install menus*)
  443.     Memory.DisposHandle(menuBar);
  444.     Menus.AddResMenu(Menus.GetMHandle(mApple), LONG("DRVR"));    (*add DA names to Apple menu*)
  445.     Menus.DrawMenuBar;
  446.  
  447.     gStopped := TRUE;
  448.     IF ¬GoGetRect(rStopRect, gStopRect) THEN
  449.         AlertUser;                            (*the stop light rectangle*)
  450.     END;
  451.     IF ¬GoGetRect(rGoRect, gGoRect) THEN
  452.         AlertUser;                            (*the go light rectangle*)
  453.     END
  454. END Initialize;
  455.  
  456.  
  457. (**************************************************************************************
  458. 1.01 - PROCEDURE DoCloseBehind(window: WindowPtr); was removed.
  459.  
  460. (*1.01 - DoCloseBehind was a good idea for closing windows when quitting
  461.  and not having to worry about updating the windows, but it suffered
  462.  from a fatal flaw. If a desk accessory owned two windows, it would
  463.  close both those windows when CloseDeskAcc was called. When DoCloseBehind
  464.  got around to calling DoCloseWindow for that other window that was already
  465.  closed, things would go very poorly. Another option would be to have a
  466.  procedure, GetRearWindow, that would go through the window list and return
  467.  the last window. Instead, we decided to present the standard approach
  468.  of getting and closing FrontWindow until FrontWindow returns NIL. This
  469.  has a potential benefit in that the window whose document needs to be saved
  470.  may be visible since it is the front window, therefore decreasing the
  471.  chance of user confusion. For aesthetic reasons, the windows in the
  472.  application should be checked for updates periodically and have the
  473.  updates serviced.*)
  474. **************************************************************************************)
  475.  
  476.  
  477. (*$S Main*)
  478. PROCEDURE Terminate;
  479.  
  480. (*Clean up the application and exits. We close all of the windows so that
  481.  they can update their documents, if any.*)
  482.  
  483. (*1.01 - If we find out that a cancel has occurred, we won't exit to the
  484.  shell, but will return instead.*)
  485.  
  486. VAR
  487.     aWindow    : Windows.WindowPtr;
  488.     closed    : BOOLEAN;
  489.  
  490. BEGIN
  491.     closed := TRUE;
  492.     REPEAT
  493.         aWindow := Windows.FrontWindow();                    (*get the current front window*)
  494.         IF aWindow # NIL THEN
  495.             closed := DoCloseWindow(aWindow)    (*close this window*)
  496.         END
  497.     UNTIL (¬closed) OR (aWindow = NIL);        (*do all windows*)
  498.     IF closed THEN
  499.         SegLoad.ExitToShell;                            (*exit if no cancellation*)
  500.     END;
  501. END Terminate;
  502.  
  503.  
  504. (*$S Main*)
  505. PROCEDURE SetLight(window: Windows.WindowPtr; newStopped: BOOLEAN);
  506.  
  507. (*Change the setting of the light.*)
  508.  
  509. BEGIN
  510.     IF newStopped # gStopped THEN
  511.         gStopped := newStopped;
  512.         Quickdraw.SetPort(window);
  513.         Windows.InvalRect(window.portRect);
  514.     END;
  515. END SetLight;
  516.  
  517.  
  518. (*$S Main*)
  519. PROCEDURE AdjustMenus;
  520.  
  521. (*Enable and disable menus based on the current state.
  522.  The user can only select enabled menu items. We set up all the menu items
  523.  before calling MenuSelect or MenuKey, since these are the only times that
  524.  a menu item can be selected. Note that MenuSelect is also the only time
  525.  the user will see menu items. This approach to deciding what enable/
  526.  disable state a menu item has the advantage of concentrating all the decision-
  527.  making in one routine, as opposed to being spread throughout the application.
  528.  Other application designs may take a different approach that may or may not be
  529.  just as valid.*)
  530.  
  531. VAR
  532.     window            : Windows.WindowPtr;
  533.     menu            : Menus.MenuHandle;
  534.  
  535. BEGIN
  536.     window := Windows.FrontWindow();
  537.  
  538.     menu := Menus.GetMHandle(mFile);
  539.     IF IsDAWindow(window) THEN                (*we can allow desk accessories to be closed from the menu*)
  540.         Menus.EnableItem(menu, iClose)
  541.     ELSE
  542.         Menus.DisableItem(menu, iClose)            (*but not our traffic light window*)
  543.     END;
  544.  
  545.     menu := Menus.GetMHandle(mEdit);
  546.     IF IsDAWindow(window) THEN        (*a desk accessory might need the edit menu*)
  547.         Menus.EnableItem(menu, iUndo);
  548.         Menus.EnableItem(menu, iCut);
  549.         Menus.EnableItem(menu, iCopy);
  550.         Menus.EnableItem(menu, iPaste);
  551.         Menus.EnableItem(menu, iClear);
  552.     ELSE                            (*but we know we do not*)
  553.         Menus.DisableItem(menu, iUndo);
  554.         Menus.DisableItem(menu, iCut);
  555.         Menus.DisableItem(menu, iCopy);
  556.         Menus.DisableItem(menu, iClear);
  557.         Menus.DisableItem(menu, iPaste);
  558.     END;
  559.  
  560.     menu := Menus.GetMHandle(mLight);
  561.     IF IsAppWindow(window) THEN        (*we know that it must be the traffic light*)
  562.         Menus.EnableItem(menu, iStop);
  563.         Menus.EnableItem(menu, iGo);
  564.     ELSE
  565.         Menus.DisableItem(menu, iStop);
  566.         Menus.DisableItem(menu, iGo);
  567.     END;
  568.     Menus.CheckItem(menu, iStop, gStopped);        (*we can also determine check/uncheck state, too*)
  569.     Menus.CheckItem(menu, iGo, ¬gStopped);
  570. END AdjustMenus;
  571.  
  572.  
  573. (*$S Main*)
  574. PROCEDURE DoMenuCommand(menuResult: LONGINT);
  575.  
  576. (*This is called when an item is chosen from the menu bar (after calling
  577.  MenuSelect or MenuKey). It performs the right operation for each command.
  578.  It is good to have both the result of MenuSelect and MenuKey go to
  579.  one routine like this to keep everything organized.*)
  580.  
  581. VAR
  582.     menuID            : INTEGER;        (*the resource ID of the selected menu*)
  583.     menuItem        : INTEGER;        (*the item number of the selected menu*)
  584.     itemHit            : INTEGER;
  585.     daName            : Types.Str255;
  586.     daRefNum        : INTEGER;
  587.     handledByDA        : BOOLEAN;
  588.     ignore            : BOOLEAN;
  589.  
  590. BEGIN
  591.     menuID := HiWrd(menuResult);    (*use built-ins (for efficiency)...*)
  592.     menuItem := LoWrd(menuResult);    (*to get menu item number and menu number*)
  593.     CASE menuID OF
  594.         mApple:
  595.             IF menuItem=iAbout THEN            (*bring up alert for About*)
  596.                 itemHit := Dialogs.Alert(rAboutAlert, NIL);
  597.             ELSE        (*all non-About items in this menu are DAs*)
  598.                 Menus.GetItem(Menus.GetMHandle(mApple), menuItem, daName);
  599.                 daRefNum := Desk.OpenDeskAcc(daName);
  600.             END|
  601.         mFile:
  602.             CASE menuItem OF
  603.                 iNew: |
  604.                 iClose:
  605.                     ignore := DoCloseWindow(Windows.FrontWindow())| (*we don't care if cancelled*)
  606.                 iQuit:
  607.                     Terminate|
  608.                 ELSE (* ignore other items *)
  609.             END|
  610.         mEdit:                        (*call SystemEdit for DA editing & MultiFinder*)
  611.             handledByDA := Desk.SystemEdit(menuItem-1)|    (*since we don't do any editing*)
  612.         mLight:
  613.             CASE menuItem OF
  614.                 iStop:
  615.                     SetLight(Windows.FrontWindow(), TRUE)|
  616.                 iGo:
  617.                     SetLight(Windows.FrontWindow(), FALSE)|
  618.                 ELSE (* ignore other items *)
  619.             END
  620.     END;
  621.     Menus.HiliteMenu(0);                    (*unhighlight what MenuSelect (or MenuKey) hilited*)
  622. END DoMenuCommand;
  623.  
  624.  
  625. (*$S Main*)
  626. PROCEDURE DrawWindow(window: Windows.WindowPtr);
  627.  
  628. (*Draw the contents of the application window. We do some drawing in color, using
  629.  Classic QuickDraw's color capabilities. This will be black and white on old
  630.  machines, but color on color machines. At this point, the window's visRgn is
  631.  set to allow drawing only where it needs to be done.*)
  632.  
  633. BEGIN
  634.     Quickdraw.SetPort(window);
  635.  
  636.     Quickdraw.EraseRect(window.portRect);    (*clear out any garbage that might be left behind*)
  637.     IF gStopped THEN                (*draw a red (or white) stop light*)
  638.         Quickdraw.ForeColor(Quickdraw.redColor)
  639.     ELSE
  640.         Quickdraw.ForeColor(Quickdraw.whiteColor)
  641.     END;
  642.     Quickdraw.PaintOval(gStopRect);
  643.     Quickdraw.ForeColor(Quickdraw.blackColor);
  644.     Quickdraw.FrameOval(gStopRect);
  645.     IF ¬gStopped THEN            (*draw a green (or white) go light*)
  646.         Quickdraw.ForeColor(Quickdraw.greenColor)
  647.     ELSE
  648.         Quickdraw.ForeColor(Quickdraw.whiteColor)
  649.     END;
  650.     Quickdraw.PaintOval(gGoRect);
  651.     Quickdraw.ForeColor(Quickdraw.blackColor);
  652.     Quickdraw.FrameOval(gGoRect);
  653. END DrawWindow;
  654.  
  655.  
  656. (*$S Main*)
  657. PROCEDURE DoContentClick(window: Windows.WindowPtr; event: Events.EventRecord);
  658.  
  659. (*This is called when a mouse-down event occurs in the content of a window.
  660.  Other applications might want to call FindControl, TEClick, etc., to
  661.  further process the click.*)
  662.  
  663. BEGIN
  664.     SetLight(window, ¬gStopped);
  665. END DoContentClick;
  666.  
  667.  
  668. (*$S Main*)
  669. PROCEDURE DoUpdate(window: Windows.WindowPtr);
  670.  
  671. (*This is called when an update event is received for a window.
  672.  It calls DrawWindow to draw the contents of an application window.
  673.  As an effeciency measure that does not have to be followed, it
  674.  calls the drawing routine only if the visRgn is non-empty. This
  675.  will handle situations where calculations for drawing or drawing
  676.  itself is very time-consuming.*)
  677.  
  678. BEGIN
  679.     IF IsAppWindow(window) THEN
  680.         Windows.BeginUpdate(window);                    (*sets up the visRgn, clears updateRgn*)
  681.         IF ¬Quickdraw.EmptyRgn(window.visRgn) THEN    (*draw if updating needs to be done*)
  682.             DrawWindow(window)
  683.         END;
  684.         Windows.EndUpdate(window);                        (*restores the visRgn*)
  685.     END
  686. END DoUpdate;
  687.  
  688.  
  689. (*$S Main*)
  690. PROCEDURE DoActivate(window: Windows.WindowPtr; becomingActive: BOOLEAN);
  691.  
  692. (*This is called when a window is activated or deactivated.
  693.  In Sample, the Window Manager's handling of activate and
  694.  deactivate events is sufficient. Other applications may have
  695.  TextEdit records, controls, lists, etc., to activate/deactivate.*)
  696.  
  697. BEGIN
  698.     IF IsAppWindow(window) THEN
  699.         IF becomingActive THEN
  700.             (*do whatever you need to at activation*)
  701.         ELSE
  702.             (*do whatever you need to at deactivation*)
  703.         END
  704.     END
  705. END DoActivate;
  706.  
  707.  
  708. (*$S Main*)
  709. PROCEDURE GetGlobalMouse(VAR mouse: Types.Point);
  710.  
  711. (*Get the global coordinates of the mouse. When you call OSEventAvail
  712.  it will return either a pending event or a null event. In either case,
  713.  the where field of the event record will contain the current position
  714.  of the mouse in global coordinates and the modifiers field will reflect
  715.  the current state of the modifiers. Another way to get the global
  716.  coordinates is to call GetMouse and LocalToGlobal, but that requires
  717.  being sure that thePort is set to a valid port.*)
  718.  
  719. VAR
  720.     event    : Events.EventRecord;
  721.     
  722. BEGIN
  723.     IF Events.OSEventAvail(kNoEvents, event) THEN END;    (*we aren't interested in any events*)
  724.     (*$TYPECHECK- no type checks please*)
  725.     mouse := event.where;                    (*just the mouse position*)
  726.     (*$TYPECHECK+ type checks please*)
  727. END GetGlobalMouse;
  728.  
  729.  
  730. (*$S Main*)
  731. PROCEDURE AdjustCursor(mouse: Types.Point; region: Quickdraw.RgnHandle);
  732.  
  733. (*Change the cursor's shape, depending on its position. This also calculates the region
  734.  where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  735.  that region, an event is generated, causing this routine to be called. This
  736.  allows us to change the region to the region the mouse is currently in. If
  737.  there is more to the event than just “the mouse moved”, we get called before the
  738.  event is processed to make sure the cursor is the right one. In any (ahem) event,
  739.  this is called again before we fall back into WNE.*)
  740.  
  741.  
  742. VAR
  743.     window                : Windows.WindowPtr;
  744.     arrowRgn            : Quickdraw.RgnHandle;
  745.     plusRgn                : Quickdraw.RgnHandle;
  746.     globalPortRect        : Types.Rect;
  747.     aCursor                : Quickdraw.CursHandle;
  748.  
  749. BEGIN
  750.     window := Windows.FrontWindow();    (*we only adjust the cursor when we are in front*)
  751.     IF (¬gInBackground) AND (¬IsDAWindow(window)) THEN
  752.         (*calculate regions for different cursor shapes*)
  753.         arrowRgn := Quickdraw.NewRgn();
  754.         plusRgn := Quickdraw.NewRgn();
  755.  
  756.         (*start with a big, big rectangular region*)
  757.         (*1.01 - changed to kExtremeNeg and kExtremePos for consistency*)
  758.         Quickdraw.SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg,
  759.                             kExtremePos, kExtremePos);
  760.  
  761.         (*calculate plusRgn*)
  762.         IF IsAppWindow(window) THEN
  763.             Quickdraw.SetPort(window);            (*make a global version of the portRect*)
  764.             Quickdraw.SetOrigin(-window.portBits.bounds.topLeft.h,
  765.                                 -window.portBits.bounds.topLeft.v);
  766.             globalPortRect := window.portRect;
  767.             Quickdraw.RectRgn(plusRgn, globalPortRect);
  768.             Quickdraw.SectRgn(plusRgn, window.visRgn, plusRgn);
  769.             Quickdraw.SetOrigin(0, 0);
  770.         END;
  771.  
  772.         (*subtract other regions from arrowRgn*)
  773.         Quickdraw.DiffRgn(arrowRgn, plusRgn, arrowRgn);
  774.  
  775.         (*change the cursor and the region parameter*)
  776.         IF Quickdraw.PtInRgn(mouse, plusRgn) THEN
  777.             aCursor:=ToolUtils.GetCursor(ToolUtils.plusCursor);
  778.             Quickdraw.SetCursor(aCursor^);
  779.             Quickdraw.CopyRgn(plusRgn, region);
  780.         ELSE
  781.             Quickdraw.SetCursor(Quickdraw.arrow);
  782.             Quickdraw.CopyRgn(arrowRgn, region);
  783.         END;
  784.  
  785.         (*get rid of our local regions*)
  786.         Quickdraw.DisposeRgn(arrowRgn);
  787.         Quickdraw.DisposeRgn(plusRgn);
  788.     END;
  789. END AdjustCursor;
  790.  
  791.  
  792. (*$S Main*)
  793. PROCEDURE DoEvent(event: Events.EventRecord);
  794.  
  795. (*Do the right thing for an event. Determine what kind of event it is, and call
  796.  the appropriate routines.*)
  797.  
  798. VAR
  799.     part, err    : INTEGER;
  800.     window        : Windows.WindowPtr;
  801.     key            : CHAR;
  802.     aPoint        : Types.Point;
  803.  
  804. BEGIN
  805.     CASE event.what OF
  806.         Events.mouseDown:
  807.             part := Windows.FindWindow(event.where, window);
  808.             CASE part OF
  809.                 Windows.inMenuBar:            (*process the menu command*)
  810.                     AdjustMenus;
  811.                     DoMenuCommand(Menus.MenuSelect(event.where))|
  812.                 Windows.inSysWindow:                (*let the system handle the mouseDown*)
  813.                     Desk.SystemClick(event, window)|
  814.                 Windows.inContent:
  815.                     IF window # Windows.FrontWindow() THEN
  816.                         Windows.SelectWindow(window);
  817.                         (*DoEvent(event);*)    (*use this line for "do first click"*)
  818.                     ELSE
  819.                         DoContentClick(window, event)
  820.                     END|
  821.                 Windows.inDrag:                        (*pass screenBits.bounds to get all gDevices*)
  822.                     Windows.DragWindow(window, event.where, Quickdraw.screenBits.bounds)|
  823.                 Windows.inGrow:|
  824.                 Windows.inZoomIn, Windows.inZoomOut:|
  825.                 ELSE (* ignore other parts*)
  826.             END|
  827.         Events.keyDown, Events.autoKey:                (*check for menukey equivalents*)
  828.             key := CHR(BAND(event.message, Events.charCodeMask));
  829.             IF BAND(event.modifiers, Events.cmdKey) # 0 THEN    (*Command key down*)
  830.                 IF event.what = Events.keyDown THEN
  831.                     AdjustMenus;            (*enable/disable/check menu items properly*)
  832.                     DoMenuCommand(Menus.MenuKey(key));
  833.                 END
  834.             END|                            (*call DoActivate with the window and...*)
  835.         Events.activateEvt:                        (*TRUE for activate, FALSE for deactivate*)
  836.             DoActivate(Windows.WindowPtr(event.message),
  837.                        BAND(event.modifiers, Events.activeFlag) # 0)|
  838.         Events.updateEvt:                          (*call DoUpdate with the window to update*)
  839.             DoUpdate(Windows.WindowPtr(event.message))|
  840.         (*1.01 - It is not a bad idea to at least call DIBadMount in response
  841.          to a diskEvt, so that the user can format a floppy.*)
  842.         Events.diskEvt:
  843.             IF HiWrd(event.message) # Types.noErr THEN
  844.                 Quickdraw.SetPt(aPoint, kDILeft, kDITop);
  845.                 err := DiskInit.DIBadMount(aPoint, event.message);
  846.             END|
  847.         kOSEvent:
  848.             CASE BAND(SYSTEM.ROT(event.message, 8), $FF) OF    (*high byte of message*)
  849.                 kSuspendResumeMessage:
  850.                     gInBackground := BAND(event.message, kResumeMask) = 0;
  851.                     DoActivate(Windows.FrontWindow(), ¬gInBackground);
  852.                 ELSE (* ignore other events *)
  853.             END;
  854.         ELSE (* ignore other events *)
  855.     END;
  856. END DoEvent;
  857.  
  858.  
  859. (*$S Main*)
  860. PROCEDURE EventLoop;
  861.  
  862. (*Get events forever, and handle them by calling DoEvent.
  863.  Get the events by calling WaitNextEvent, if it's available, otherwise
  864.  by calling GetNextEvent. Also call AdjustCursor each time through the loop.*)
  865.  
  866. VAR
  867.     cursorRgn    : Quickdraw.RgnHandle;
  868.     gotEvent    : BOOLEAN;
  869.     event        : Events.EventRecord;
  870.     mouse        : Types.Point;
  871.  
  872. BEGIN
  873.     cursorRgn := Quickdraw.NewRgn();                (*we’ll pass WNE an empty region the 1st time thru*)
  874.     LOOP
  875.         IF gHasWaitNextEvent THEN    (*put us 'asleep' forever under MultiFinder*)
  876.             GetGlobalMouse(mouse);        (*since we might go to sleep*)
  877.             AdjustCursor(mouse, cursorRgn);
  878.             gotEvent := Events.WaitNextEvent(Events.everyEvent, event, MAX(LONGINT), cursorRgn);
  879.         ELSE
  880.             Desk.SystemTask;                    (*must be called if using GetNextEvent*)
  881.             gotEvent := Events.GetNextEvent(Events.everyEvent, event);
  882.         END;
  883.         IF gotEvent THEN
  884.             AdjustCursor(event.where, cursorRgn);    (*make sure we have the right cursor*)
  885.             DoEvent(event);
  886.         END;
  887.         (*If you are using modeless dialogs that have editText items,
  888.          you will want to call IsDialogEvent to give the caret a chance
  889.          to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  890.          for a non-NIL value before calling IsDialogEvent.*)
  891.     END                        (*loop forever; we quit through an ExitToShell*)
  892. END EventLoop;
  893.  
  894.  
  895. PROCEDURE _DataInit; EXTERNAL;
  896.  
  897. (*This routine is part of the MPW runtime library. This external
  898.  reference to it is done so that we can unload its segment, %A5Init.*)
  899.  
  900. (*$S Main*)
  901. (*$MAIN*)
  902. BEGIN
  903.     SegLoad.UnloadSeg(SYSTEM.ADR(_DataInit));    (*note that _DataInit must not be in Main!*)
  904.     
  905.     (*1.01 - call to ForceEnvirons removed*)
  906.     (*If you have stack requirements that differ from the default,
  907.      then you could use SetApplLimit to increase StackSpace at 
  908.      this point, before calling MaxApplZone.*)
  909.      
  910.     Memory.MaxApplZone;            (*expand the heap so code segments load at the top*)
  911.  
  912.     Initialize;                (*initialize the program*)
  913.     SegLoad.UnloadSeg(SYSTEM.ADR(Initialize));    (*note that Initialize must not be in Main!*)
  914.  
  915.     EventLoop;                (*call the main event loop*)
  916. END Sample.
  917.